<?php

class Common extends Model
{

	function Intro()
		{
			parent::Model();	
		}//end method

		
	function authenticate()
		{	
			$datas		= array();													//initialize array
			$this->load->helper('common');											//load common helper module
			$this->load->helper('form');
			$this->load->helper('url');
			$siteVars	= $this->getSiteVars();
			if($this->session->userdata('user_id'))
				{
					//echo "hi".base_url();
					$datas['userId']			= $this->session->userdata('user_id');				//store current user id
					$datas['currentPage']		= base_url();						//store current site base url
					$datas['loggedIn']			= true;								//set login status as true
					$datas['siteTitle']			= $siteVars['siteTitle'];
					$datas['siteName']			= $siteVars['siteName'];
					$userName					= $this->getUsername($this->session->userdata('user_id'));
					$datas['userName']			= $userName;
				}
			else
				{
					$currentUrl				= $_SERVER['REQUEST_URI'];	//assign current url
					$this->session->set_userdata('loginUrl', ''.$currentUrl.'');
				}
			return $datas;												//returns array 
		}//end authenticate
	

	function basicvars()
		{	
			$datas		= array();													//initialize array
			$this->load->helper('common');											//load common helper module
			$this->load->helper('form');
			$this->load->helper('url');
			$siteVars	= $this->getSiteVars();
			if($this->session->userdata('user_id'))
				$datas['loggedIn']		= true;	
			else
				$datas['loggedIn']		= false;	
			//echo "hi".base_url();
			$datas['currentPage']		= base_url();						//store current site base url
			$datas['siteTitle']			= $siteVars['siteTitle'];
			$datas['siteName']			= $siteVars['siteName'];
			return $datas;												//returns array 
		}//end basicvars()
		
	function getAvatar($userid)
		{
			$avatarko	= './application/images/pictures/'.$userid.'/60x60.jpg';
			if(isFileExists($avatarko))//if directory exist for this user, remove image
				$userAvatar	= base_url().$avatarko;
			else
				$userAvatar	= base_url().'application/images/question_b.gif';
			//echo $userAvatar;
			return $userAvatar;
		}//end getAvatar()

		
	function getLargeAvatar($userid)
		{
			$profileRs	= getRow("picture_profile","picture_path","user_id='$userid'");
			if($profileRs['picture_path']=='')
				$userAvatar	= base_url().'application/images/question_y.gif';
			else
			{
				$userAvatar	= $profileRs['picture_path'];
			}
			return $userAvatar;
		}//end getAvatar()

		
	function getUsername($userid)
		{
			$userRs		= getRow("users","firstname, lastname","user_id='$userid'");
			return ucwords(''.$userRs['firstname'].' '.$userRs['lastname'].'');
		}

		
	function validMonthDay($month,$day)
		{
			//echo $month;
			$valid	= true;
			if(strtoupper($month)=='02' and $day>28)
				$valid=false;
			if(strtoupper($month)=='04' and $day>30)
				$valid=false;
			if(strtoupper($month)=='06' and $day>30)
				$valid=false;
			if(strtoupper($month)=='09' and $day>30)
				$valid=false;
			if(strtoupper($month)=='11' and $day>30)
				$valid=false;
			return $valid;
		}//end validMonthDay()


		
	function getSiteVars()
		{	
			$data					= array();								//initialize array
			$data['adminName']		= 'Адміністрація';				//Admin Name
			$data['adminEmail']		= 'admin@domain.ltd';
			$data['siteTitle']		= 'Балачка';
			$data['siteName']		= 'domain.tld';				//site name

			return $data;
		}//end getSiteVars

		
	function getSingleProfile($userId,$userID,$type='')
		{
			//echo 'hi'.$userId;
			$usrRs		= getRow("users", "firstname, lastname", "user_id='$userID'");
			$username	= ''.$usrRs['firstname'].' '.$usrRs['lastname'].'';
			$viewUrl	= base_url()."friends/view/".$userID;
			$sendUrl	= base_url()."messages/compose/".$userID;
			$removeUrl	= base_url()."friends/remove/".$userID;
			$addUrl		= base_url()."friends/add/".$userID;
			$profileUrl = base_url()."user/profile/".$userID;
			$avatar		= $this->getAvatar($userID);
			if($userID==$userId)
			{
				$avatarContent	= '<a href="'.$profileUrl.'"><img src="'.$avatar.'" border="0" class="photo" width="100"></a>';	
				$actionContent	=	'<div><a href="'.$viewUrl.'">Переглянути друзів</a></div>';
			}
			else
				{
					$isUrFriend		= getTotRec("friends_list_id","friends_list","user_id='$userId' AND friend_id='$userID'");
					if ($type=='search')
					{
						if($isUrFriend>0)
							$add2friends	= '';
						else
						{
							$add2friends	= 	'<div><a href="'.$addUrl.'">Додати до друзів</a></div>'; 
						}


						$viewFriends	= '<div><a href="'.$viewUrl.'">Переглянути друзів</a></div>';

						$avatarContent	= '<a href="'.$profileUrl.'"><img src="'.$avatar.'" border="0" class="photo" width="100"></a>';	
						
						$sendMessage ='<div><a href="'.$sendUrl.'">Надіслати повідомлення</a></div>';
					}
					else
					{
					if($isUrFriend>0)
						$add2friends	= '';
					else
						$add2friends	= '<div><a href="'.$addUrl.'">Додати до друзів</a></div>'; 
						$viewFriends	= '<div><a href="'.$viewUrl.'">Переглянути друзів</a></div>';
						$avatarContent	= '<a href="'.$profileUrl.'"><img src="'.$avatar.'" border="0" class="photo" width="100"></a>';	
						$sendMessage 	= '<div><a href="'.$sendUrl.'">Надіслати повідомлення</a></div>';
					}
						
					$actionContent		= $sendMessage.$viewFriends.$add2friends;

				}
				
				$content	=	' 
								<div class="friends_result" style="width: 356px; float: left; ">
								<table cellpadding="0" cellspacing="0">
								<tr>
								<td class="friends_result0"><div class="list2"><span><div><a href= '.$profileUrl.'><img src="'.$avatar.'" border="0"></a></div></span></div></td>
								<td class="friends_result1" width="100%" valign="top" style="padding:10px; padding-left:0;">
								  <div class="friends_name"><a href="'.$profileUrl.'">'.$username.'</a></div>
								  '.$this->offline($userID, 'friends').'
								</td>
								<td class="friends_result2" valign="top" nowrap="nowrap">'.$actionContent.'</td>
								</tr>
								</table>
								</div>
								';
			return $content;
		}//end getSingleProfile()	

	function getOnlineFriends($userID)
		{
			//echo 'hi'.$userId;
			$usrRs		= getRow("users", "firstname, lastname", "user_id='$userID'");
			$username	= ''.$usrRs['firstname'].' '.$usrRs['lastname'].'';
			$profileUrl = base_url()."user/profile/".$userID;
			$avatar		= $this->getAvatar($userID);

			$сontent	= '<li><div><a href="'.$profileUrl.'"  class="addToolTip" title="'.$username.'"><img src="'.$avatar.'" width="60" height="60" border="0" /></a></div></li>';

			return $сontent;
		}//end getSingleProfile()	
		
		

	
		
	
	function getFriends($userId)
		{
			$friendsArray	= array();
			$query	= 	"SELECT friend_id AS FriendId FROM `friends_list` WHERE user_id='$userId' and approved_status='yes' 
						UNION
						SELECT user_id as FriendId FROM `friends_list` WHERE friend_id='$userId' and approved_status='yes' ";
			$res	= mysql_query($query);
			if($res)
				{
					$totFriends	= mysql_num_rows($res);
					if($totFriends>0)
						while($rs=mysql_fetch_object($res))
							$friendsArray[]	= $rs->FriendId;
				}//end res
			return $friendsArray;
		}//end getFriends()

		
	function welcomeFriendsRequest($userId)
		{
			$friendRequestUrl	= base_url().'friends/request';
			$mainContent= '';
			$sql=mysql_query("SELECT user_id FROM `friends_list` WHERE `friend_id` =$userId and approved_status='no'"); //fetching the list request friend 
			if ($sql)
			{
			while($rs=mysql_fetch_object($sql))
				{
					$tot		=getTotRec("user_id","friends_list","friend_id='$userId' AND approved_status='no'");
					$totRequest	= $tot;
					if($totRequest>0)
						{
							$content	= 	'<tr><td><div><a href="'.$friendRequestUrl.'"><img src="'.base_url().'application/images/friend.gif" border="0"> Вхідні запити на дружбу ('.$totRequest.')</a></div></td></tr>';
							$mainContent= 	'<table width="100%" border="0" cellspacing="4" cellpadding="0">'.$content.'</table>';
						}
				}
			}
			return $mainContent;
		}//end friendsRequest()

		
	function listUsers($resultSet,$userId)
		{
			$i			= 0;
			$content	= '';
			if($resultSet)
			while($rs = mysql_fetch_object($resultSet))
				{

					$content	.=	$this->getSingleProfile($userId,$rs->user_id,$type='search');
					
						
					$i++;
				}//end while

				$contents	=	$content;
				return $contents;
		}//end listFriends()
		


	function listMessage($query,$action)
		{
			$this->load->helper('typography');
			$siteVars	= $this->common->getSiteVars();
			$res		= mysql_query($query);//execute query
			$currentPage= base_url();
			//checks query xecuted successfully
			if($res)
				{
					$rows	= mysql_num_rows($res);
					$i		= 1;

					$recPerPage = 20;
					$config['base_url'] 	= base_url().'messages/'.$action.'/page/';
					$config['total_rows'] 	= $rows;
					$config['per_page'] 	= $recPerPage;
					$config['uri_segment']	= 4;
					$config['full_tag_open'] = '<ul class="prev-next skin-default_pager">';
					$config['full_tag_close'] = '</ul>';
					$config['cur_tag_open'] = '<li class="active">';
					$config['cur_tag_close'] = '</li>';
					$config['num_tag_open'] = '<li>';
					$config['num_tag_close'] = '</li>';
					$config['prev_link'] = '&larr;';
					$config['next_link'] = '&rarr;';
					$config['prev_tag_open'] = '<li>';
					$config['prev_tag_close'] = '</li>';					
					$config['next_tag_open'] = '<li>';
					$config['next_tag_close'] = '</li>';
					$config['first_link'] = 'на початок';
					$config['first_tag_open'] = '<li>';
					$config['first_tag_close'] = '</li>';
					$config['last_link'] = 'в кінець';
					$config['last_tag_open'] = '<li>';
					$config['last_tag_close'] = '</li>';
					
					$this->pagination->initialize($config);
					if($this->uri->segment(4)!='')
						$offSet	= $this->uri->segment(4);
					else
						$offSet	= 0;
					if($offSet>0)
						$startLimit	= ($offSet/$recPerPage)*$recPerPage;
					else
						$startLimit	= 0;
					$endLimit	= $recPerPage;
					$pageLink	= $this->pagination->create_links();//end paging
					
					$pageQuery	= $query." LIMIT ".$startLimit.",".$endLimit;
					$pageRes	= mysql_query($pageQuery);
					if($pageRes)
						while($rs= mysql_fetch_object($pageRes)) {
							if($action=='inbox')
								{
									$usrRs		= getRow('users',"firstname, lastname","user_id='$rs->from_id'");
									$userName	= ucwords($usrRs['firstname'].' '.$usrRs['lastname']);		//user name
									$msgId		= $rs->inbox_message_id;
									$singleChk	= "inbox_".$rs->inbox_message_id;
									
									if($rs->message_status=='read') {
										$chkBoxName	= 'mess_i_r_'.$i;//inbox read message
										$style ='messages_read';
									}
									else
									{
										$chkBoxName	= 'mess_i_u_'.$i;//inbox unread message
										$style ='messages_unread';
									}
									//echo $rs->from_id;
									$senderId		= $rs->from_id;
									$jsArgMsgName	= 'mess_i_';
									$readUrl		= base_url().'messages/read/i_'.$msgId;
								}
							else
								{

									$usrRs		= getRow('users',"firstname, lastname","user_id='$rs->to_id'");
									$userName	= ucwords($usrRs['firstname'].' '.$usrRs['lastname']);		//user name
									$msgId		= $rs->message_id;
									$singleChk	= "sent_".$rs->message_id;
									$senderId	= $rs->to_id;
									
									if($rs->message_status=='read')
										$chkBoxName	= 'mess_s_r_'.$i;//sent read message
									else
										$chkBoxName	= 'mess_s_u_'.$i;//sent unread message
										
									$jsArgMsgName	= 'mess_s_';
									$readUrl	= base_url().'messages/read/s_'.$msgId;
								}
							
							//date and time of message sent	
							$actualDate	= strtotime($rs->datestamp);
							$sentDate	= date('d.m.Y',$actualDate);
							$sentTime	= date('h:i',$actualDate);
							$avatar 	= $this->getAvatar($senderId);
														
							$profileUrl	= base_url()."user/profile/".$senderId."";
							
							if (strlen($rs->message) > 100) 
								$dots = '...';

							$msgList	.= '<tr class="'.$style.'">
										    <td class="messages_message" width="1" align="center"><input type=checkbox name="'.$chkBoxName.'" id="'.$chkBoxName.'" onclick = "checkedMsg(\''.$action.'\')" value="'.$msgId.'"></td>
										    <td class="messages_message" width="1"><div class="list2"><span><div><a href= '.$profileUrl.'><img src="'.$avatar.'" border="0"></a></div></span></div></td>
										    <td class="messages_message" width="130" nowrap="nowrap" valign="middle">
										      <b><a href="'.$profileUrl.'">'.$userName.'</a></b>
										      <div class="messages_date">'.$sentDate.' @ '.$sentTime.'</div>
											  '.$this->offline($senderId, 'message').'
										    </td>
										    <td class="messages_message" width="100%">
												<strong><a href="'.$readUrl.'">'.$rs->subject.'</a></strong>
												<div class="messageBody"><a href="'.$readUrl.'">'.nl2br_except_pre(substr($rs->message, 0, strrpos(substr($rs->message, 0, 100), ' '))).''.$dots.'</a></div>
										    </td>
										    <td class="messages_message" align="right" nowrap="nowrap">
										      <a href="javascript:void(0);" style="text-decoration:none;" onclick="javascript:msgSingleDelete(\''.$singleChk.'\',\''.$currentPage.'\',\''.$action.'\');">Видалити</a>
										    </td>
										    </tr>
											';
							
							$i++;
							
						}
								

				}//end if
		
									

			$checkLength	= $i-1;
			//if message exist, prepare message list
			if($rows>0)
				{

					$option		= '<table cellpadding=4 cellspacing=0 style="margin-bottom:10px">
									<tr>
										<td>
											<b>Виділіти:</b> <a href="javascript:void(0);" onclick="sel_message(\'all\',\''.$checkLength.'\',\''.$action.'\')">всі</a>, <a href="javascript:void(0);" onclick="sel_message(\'none\',\''.$checkLength.'\',\''.$action.'\')">жодного</a>,<a href="javascript:void(0);" onclick="sel_message(\'read\',\''.$checkLength.'\',\''.$action.'\')">прочитані</a>, <a href="javascript:void(0);" onclick="sel_message(\'unread\',\''.$checkLength.'\',\''.$action.'\')">непрочитані</a>
										</td>
										<td>
											<div id="message_action_option"></div>
										</td>						
									</tr>
									</table>';
									
				if($action == 'inbox')
					{
						$mailAs	= 'Відправник';
					}
				else
					{
						$mailAs	= 'Отримувач';
					}
//$option									
					$content	=	'
					'.$option.'
					<div id="tabMessages">
									<form name="msgForm" method="post" id="msgForm" enctype="multipart/form-data">

												<div class="pager">'.$pageLink.'</div>
												<table class="messages_table" cellpadding="0" cellspacing="0" width="100%">
												  <tr>
												  <td class="messages_header"><input type=\'checkbox\' name=\'checkall\' id=\'checkall\' onclick="if (this.value == \'1\') {sel_message(\'none\',\''.$checkLength.'\',\''.$action.'\'); this.value = \'0\';} else {sel_message(\'all\',\''.$checkLength.'\',\''.$action.'\'); this.value = \'1\';}"></td>
												  <td class="messages_header" colspan="2">'.$mailAs.'</td>
												  <td class="messages_header" colspan="2" style="border-right:0;">Тема</td>
												  </tr>
												 '.$msgList.'
												</table>
												<div class="pager">'.$pageLink.'</div>
										<input type="hidden" name="msgCnt" id="msgCnt" value="'.$rows.'">
										</form>
										</div>';
				}
			else//else show no message
				$content	='<table cellpadding=4 cellspacing=0 width=100% class=b_a>
							  <tr height="100"><td colspan="4" align="center" valign="center"><strong>Наразі у вас немає жодного повідомлення</strong></td></tr>
							  </table>';
					
			return $content;
		}

	//store user details to inbox_message table
	function store2Inbox($toid,$subject,$message)
		{
			global $userId,$now;
			//store mail info into inbox_messages table
			$inboxFieldList	= "from_id='$userId',user_id='$toid', subject='$subject', message='$message',datestamp='$now'";
			if(insertRecord('inbox_messages',$inboxFieldList))
				return true;
			else
				return false;
		}
	//store user details to messages table
	function store2Sent($toid,$subject,$message,$type,$typeValue='')
		{
			global $userId,$now;
			//store info at messages table as sent item
			$fieldList	= "user_id='$userId', to_id='$toid', subject='$subject', message='$message',datestamp='$now',to_name='$typeValue',to_type='$type'";
			if(insertRecord('messages',$fieldList))
				return true;
			else
				 return false;
		}
	//function to prepare friends list,
	//to show on groups member page


	function countFriendRequest($userId)
		{
			$content= '';
			$sql=mysql_query("SELECT user_id FROM `friends_list` WHERE `friend_id` =$userId and approved_status='no'"); //fetching the list request friend 
			if ($sql)
			{
			while($rs=mysql_fetch_object($sql))
				{
					$sqlrec	=mysql_query("select user_id,blocked_user_id from block_users where user_id=".$userId." and  blocked_user_id=".$rs->user_id); //checking if the requested friend is blocked user or not
					$cnt	= mysql_num_rows($sqlrec);
					if($sqlrec)
						{
							while($res=mysql_fetch_object($sqlrec))
								{
								$qry=mysql_query("delete from friends_list where user_id=".$res->blocked_user_id." and friend_id=".$res->user_id); // deleting the requested friend if the requested friend is blocked person 
								}
						}
					$tot		=getTotRec("user_id","friends_list","friend_id='$userId' AND approved_status='no'");
					$totRequest	= $tot-$cnt;
					if($totRequest>0)
						{
							$content	= 	'(<b>'.$totRequest.'</b>)';
						}
				}
			}
			return $content;
		}//end countFriendRequest()

	function countNewMsg($userId)
		{
			$content= '';
			$sql=mysql_query("SELECT user_id FROM `inbox_messages` WHERE `user_id` = '$userId' and message_status='unread'"); //fetching the list request friend 
			if ($sql)
			{
			while($rs=mysql_fetch_object($sql))
				{
					$tot		=getTotRec("user_id","inbox_messages","user_id='$userId' AND message_status='unread'");
					$totRequest	= $tot;
					if($totRequest>0)
						{
							$content	= 	'(<b>'.$totRequest.'</b>)';
						}
				}
			}
			return $content;
		}//end countFriendRequest()
		
	function countWallMsg($profileId)
		{
			$content= '';
			$sql=mysql_query("SELECT posted_to FROM `profile_wall` WHERE `posted_to` = '$profileId'"); //fetching the list request friend 
			
			if ($sql)
			{
				while($rs=mysql_fetch_object($sql))
					{
						$tot		=getTotRec("posted_to","profile_wall","posted_to='$profileId'");
						$totRequest	= $tot;
						if($totRequest>0)
							{
								$content	= 	'(<b>'.$totRequest.'</b>)';
							}
					}
			}
			return $content;
		}//end countFriendRequest()
		
function countAllUsr()
{
	$totRec	= 0;
	$query	= 	"SELECT user_id FROM `users` WHERE user_status = 'active'";
	$res	= mysql_query($query);
	if($res)
		$totRec	= mysql_num_rows($res);
	return $totRec;
}//end countAllUsr()

function countOutRequest($userId)
{
	$content= '';
	$sql=mysql_query("SELECT friend_id FROM friends_list WHERE user_id='$userId' AND approved_status='no'"); //fetching the list request friend 
	if ($sql)
	{
	while($rs=mysql_fetch_object($sql))
		{
			$tot		=getTotRec("friend_id","friends_list","user_id='$userId' AND approved_status='no'");
			$totRequest	= $tot;
			if($totRequest>0)
				{
					$content	= 	'(<b>'.$totRequest.'</b>)';
				}				}
	}
	return $content;
}//end countOutRequest()
	
function offline($user_id, $type='')
{
	global $now;
	$content = '';
	$query	= 'SELECT last_activity, logged_in FROM ci_sessions, users WHERE user_data LIKE "%user_id_'.$user_id.'%" AND users.user_id = "'.$user_id.'" AND users.logged_in = "1"';    
//	"SELECT last_activity FROM ci_sessions WHERE user_data LIKE '%$userid%'"; 
	$res	= mysql_query($query);
	while($rs=mysql_fetch_object($res))
		{
			$tot		= getTotRec("last_activity","ci_sessions","userdata LIKE "%$user_id%"");
			$totRequest	= $tot;
			
			if($totRequest>0 && $rs->logged_in =! 0)
				{
					$currentTime	= time();
					$lastActivity	= $rs->last_activity;
					if (($currentTime - $lastActivity) <= 300) {
						if ($type == 'profile')
						$content = '<div style="background-color:#00aa00; padding:2px 5px 2px 5px; float:right; color:#fff;">на сайті</div>';
						elseif ($type == 'wall' || $type == 'message' || $type == 'friends')
						$content = '<span class="online_wall"><img src="'.base_url().'application/templates/images/icons/wall-online.png" title="на сайті" alt="на сайті"> на сайті</span>';
					}
				}
		}
	return $content;
}

function onlineFriends($user_id)
{
	$onlineFriends	= array();
	$friendFriends	= array();
	
	$query2	= 'SELECT DISTINCT friend_id FROM friends_list WHERE user_id="'.$user_id.'" AND approved_status="yes"';    
	$res2	= mysql_query($query2);

	while($rs2=mysql_fetch_object($res2))
		{
			$tot		= getTotRec("friend_id","friends_list","user_id="%$user_id%" AND approved_status=\"yes\"");
			$totRequest	= $tot;
			
			if($totRequest>0)
				{
						$friendFriends[]	= $rs2->friend_id;
				}
				
		}

	
	for($i = 0; $i < count($friendFriends); $i++) 
	{
		$query	= 'SELECT user_id, last_activity, logged_in FROM ci_sessions, users WHERE user_data LIKE "%user_id_'.$friendFriends[$i].'%" AND users.user_id = "'.$friendFriends[$i].'" AND users.logged_in = "1" LIMIT 0, 1';    
		$res	= mysql_query($query);
	
//	"SELECT last_activity FROM ci_sessions WHERE user_data LIKE '%$userid%'"; 
		while($rs=mysql_fetch_object($res))
			{
				$tot		= getTotRec("last_activity","ci_sessions","userdata LIKE "%$user_id%"");
				$totRequest	= $tot;
				
				if($totRequest>0 && $rs->logged_in != 0)
					{
						$currentTime	= time();
						$lastActivity	= $rs->last_activity;
						if (($currentTime - $lastActivity) <= 300) {
							$onlineFriends[]	= $rs->user_id;
						}
					}
					
			}
	}
	return $onlineFriends;
}	
}
	

?>
